package com.azt.back.action.order;

import com.azt.api.enums.OrderPayResultEnum;
import com.azt.api.enums.OrderStateEnum;
import com.azt.api.enums.OrderTypeEnum;
import com.azt.api.pojo.Company;
import com.azt.api.pojo.OrderInfo;
import com.azt.api.pojo.OrderPayInfo;
import com.azt.api.pojo.OrderShip;
import com.azt.api.service.CompanyService;
import com.azt.api.service.OrderPayService;
import com.azt.api.service.OrderService;
import com.azt.api.service.OrderShipService;
import com.azt.back.action.BaseAction;
import com.azt.back.util.ContextUtils;
import com.azt.back.util.Globals;
import com.azt.exception.BaseException;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.convert.Convert;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderAction extends BaseAction {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderPayService orderPayService;

    @Autowired
    private OrderShipService orderShipService;

    @Autowired
    private CompanyService companyService;

    /**
     * 载入订单管理页面
     * */
    @RequestMapping(value = "/order_list.do")
    public String listOrder(Model model) {
        model.addAttribute("orderStateMap", CommonUtil.getEnumMap(OrderStateEnum.class));

        Map searchMap = CommonUtil.getParameterMap(request);

        int pageNo = getParaToInt("pageNo", 1);
        Date edate = getParaToDate("edate");	//结束日期
        if(edate != null) {
            searchMap.put("edate", DateUtils.addDays(edate, 1));
        } else {
            searchMap.remove("edate");
        }

        Page page = PageHelper.startPage(pageNo, Globals.PAGE_SIZE);
        List<Map> list = orderService.searchMgrOrder(searchMap);

        Pagination pagination = new Pagination(page, list);
        pagination.setList(list);
        pagination.setParams(searchMap);

        model.addAttribute("pagination", pagination);

        searchMap.put("edate", getPara("edate"));
        RequestUtils.MapToModelMap(searchMap, request);

        return "order/order_list";
    }

    /**
     * 载入线下支付审核页面
     * */
    @RequestMapping(value = "/audit_list.do")
    public String listAudit(HttpServletRequest request, HttpServletResponse response, Model model) {
        Integer orderId = Convert.toInt(request.getParameter("orderId"));

        if(orderId != null) {
            model.addAttribute("order", orderService.getOrderInfoById(orderId));
            model.addAttribute("list", orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue()));
        }
        return "order/audit_list";
    }

    @ResponseBody
    @RequestMapping(value = "/audit.do", method = RequestMethod.POST)
    public AjaxJson auditOrder(HttpServletRequest request, HttpServletResponse response) {
        Integer payId = Convert.toInt(request.getParameter("payId"));
        boolean pass = Convert.toBool(request.getParameter("pass"));
        String rejectReason = request.getParameter("rejectReason");

        if(payId != null) {
            try {
                orderService.auditOrder(payId, pass, rejectReason, ContextUtils.getAdmin().getId());
                return AjaxJson.success();
            } catch (BaseException be) {
                return AjaxJson.error(be.getErrorCode());
            }
        }
        return AjaxJson.error("操作失败");
    }

    @RequestMapping(value = "/order_detail.do")
    public String orderDetail(Model model) {
        Integer orderId = getParaToInt("orderId");

        if(orderId != null) {
            OrderInfo orderInfo = orderService.getOrderInfoById(orderId);
            if(orderInfo != null) {
                //支付信息
                List<OrderPayInfo> payList = orderPayService.findOrderPay(orderId, OrderPayResultEnum.SUBMIT.getValue(), OrderPayResultEnum.REVIEW.getValue(), OrderPayResultEnum.SUCCESS.getValue());
                //发货信息
                List<OrderShip> shipList = orderShipService.findOrderShip(orderId, null, null);
                //收货信息
                model.addAttribute("address", orderService.getOrderAddress(orderId));

                Company buyer = companyService.getCompanyById(orderInfo.getBuyerCompanyId());
                Company seller = companyService.getCompanyById(orderInfo.getSellerCompanyId());
                if(buyer != null && buyer.getParentId() != null) {
                    model.addAttribute("topBuyer", companyService.getTopParentCompany(orderInfo.getBuyerCompanyId()));
                }


                List itemList = new ArrayList();
                if(orderInfo.getOrdertype().intValue() == OrderTypeEnum.ENQUIRY.getValue()) {
                    //询价订单
                    itemList = orderService.findOrderDetailByOrderId(orderId);
                } else {
                    //商品订单
                    itemList = orderService.findOrderProduct(orderId);
                }


                model.addAttribute("order", orderInfo);
                model.addAttribute("itemList", itemList);
                model.addAttribute("payList", payList);
                model.addAttribute("shipList", shipList);
                model.addAttribute("buyer", buyer);
                model.addAttribute("seller", seller);
            }
        }

        model.addAttribute("orderStateMap", CommonUtil.getEnumMap(OrderStateEnum.class));
        return "order/order_detail";
    }

    /**
     * 载入资金列表
     * */
    @RequestMapping(value = "/pay_list.do")
    public String listPay(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map searchMap = CommonUtil.getParameterMap(request);
        int pageNo = CommonUtil.safeToInt(request.getParameter("pageNo"), 1);

        Page page = PageHelper.startPage(pageNo, Globals.PAGE_SIZE);
        List<Map> list = orderService.searchMgrPayList(searchMap);

        Pagination pagination = new Pagination(page, list);
        pagination.setList(list);
        pagination.setParams(searchMap);

        model.addAttribute("pagination", pagination);

        RequestUtils.MapToModelMap(searchMap, request);

        return "order/pay_list";
    }
}